<template>
  <div class="index">
    <template
      v-for="(item, index) in formData.personnelAssessmentOption"
      :key="item.selectIndex"
    >
      <a-form
        v-show="index === selectIndex"
        :model="item"
        ref="refForm"
        :rules="rules"
        auto-label-width
        style="width: 500px; margin: 0 auto"
      >
        <a-form-item label="被考核人员" field="name" show-colon>
          <a-input
            v-model="item.userInfo.name"
            ref="refInput"
            @focus="focus"
            @change="userChange"
          />
        </a-form-item>
        <a-form-item label="考核次数" field="selectIndex" show-colon>
          <a-space :direction="'vertical'">
            <a-space direction="horizontal" size="large">
              <!-- <a-radio-group
                v-model="formDataLength"
                size="large"
                @change="changeExamineNumber"
              >
                <a-radio
                  v-for="selectIndex in 6"
                  :value="selectIndex"
                  :key="selectIndex"
                >
                  <template #radio="{ checked }">
                    <a-space
                      wrap
                      class="custom-radio-card1"
                      :class="{ 'custom-radio-card-checked': checked }"
                    >
                      <div class="custom-radio-card-title">
                        {{ selectIndex }}
                      </div>
                    </a-space>
                  </template>
                </a-radio>
              </a-radio-group> -->
              <a-input-number
                v-model="formDataLength"
                :style="{ width: '120px' }"
                placeholder="输入其他"
                class="input-demo"
                :min="1"
              />
            </a-space>
            <a-space :direction="'horizontal'" size="large" wrap>
              <a-radio-group
                size="large"
                v-model="selectIndex"
                @change="selectIndexChange"
              >
                <a-radio
                  v-for="num in formData.personnelAssessmentOption.length"
                  :key="num"
                  :value="num - 1"
                >
                  <template #radio="{ checked }">
                    <a-space
                      wrap
                      class="custom-radio-card"
                      :class="{ 'custom-radio-card-checked': checked }"
                    >
                      <div class="custom-radio-card-title">第 {{ num }} 次</div>
                    </a-space>
                  </template>
                </a-radio>
              </a-radio-group>
            </a-space>
          </a-space>
        </a-form-item>
        <a-form-item label="考核周期" field="cycleStart" show-colon>
          <a-range-picker
            v-model="rangeDate"
            @change="rangePickerChange"
            :allow-clear="false"
          />
        </a-form-item>
        <a-form-item label="预警提醒时间" field="" show-colon>
          <a-date-picker
            v-model="item.earlyWarningTime"
            :disabledDate="disabledDate"
          />
        </a-form-item>
        <a-form-item label="启动时间" field="startTime" show-colon>
          <a-date-picker
            v-model="item.startTime"
            :disabledDate="disabledDate"
          />
        </a-form-item>
      </a-form>
    </template>
  </div>
  <PersonSelectModal v-model:visible="visible" />
  <HumanRosterModal
    v-model:visible="humanRosterVisible"
    @humanRosterEmit="selectHuman"
  />
</template>

<script setup lang="ts">
import type {
  ProbationExamine,
  ProbationAppraise
} from '@/apis/human/base/variationManager/probation/type';
import { getProbationPersonnelList } from '@/apis/human/base/variationManager/probation';
import { useVModel } from '@vueuse/core';
import PersonSelectModal from './PersonSelectModal.vue';
import dayjs from 'dayjs';
import HumanRosterModal from '@/components/HumanRosterModal/index.vue';
const props = withDefaults(
  defineProps<{
    templateData: ProbationAppraise;
    currentProgrammeIndex: number;
  }>(),
  {}
);
const emit = defineEmits([
  'update:templateData',
  'update:currentProgrammeIndex'
]);

const formData = useVModel(props, 'templateData', emit);
const selectIndex = useVModel(props, 'currentProgrammeIndex', emit);

const validateName = async (value: any, cb: any) => {
  // if (value === props.templateData.cname) return;
  // const res = await ({ name: `${formData.value.name}` });
  // if (res?.code === 400) {
  //   cb('名称已存在!');
  // }
};
const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入'
    }
    // {
    //   // validator: validateName
    // }
  ],
  cycleStart: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  earlyWarningTime: [
    {
      required: true,
      message: '请输入'
    }
  ],
  startTime: [
    {
      required: true,
      message: '请输入'
    }
  ]
});
const refForm = ref();
const validate = async () => {
  let check = void 0;
  check = await refForm.value[selectIndex.value].validate();

  if (check) return check;
  let temp = selectIndex.value;
  selectIndex.value = 0;
  for await (const item of refForm.value) {
    check = await item.validate();
    if (check) return check;
    if (selectIndex.value === refForm.value.length - 1) {
      selectIndex.value = temp;
      return;
    }
    selectIndex.value++;
  }
  return;
};
//时间范围选择
// const rangeDate = ref<any[][]>([]);
const rangeDate = computed(() => {
  if (!formData.value.personnelAssessmentOption) return [];
  const { cycleStart, cycleEnd } =
    formData.value.personnelAssessmentOption[selectIndex.value];
  return [cycleStart, cycleEnd];
});
const rangePickerChange = (vals: any) => {
  if (!formData.value.personnelAssessmentOption) return;
  formData.value.personnelAssessmentOption[selectIndex.value].cycleStart =
    vals[0];
  formData.value.personnelAssessmentOption[selectIndex.value].cycleEnd =
    vals[1];
  const { cycleStart, cycleEnd, earlyWarningTime, startTime } =
    formData.value.personnelAssessmentOption[selectIndex.value];
  if (earlyWarningTime < cycleStart || earlyWarningTime > cycleEnd) {
    formData.value.personnelAssessmentOption[
      selectIndex.value
    ].earlyWarningTime = '';
  }
  //启动时间默认等于考核周期开始时间
  formData.value.personnelAssessmentOption[selectIndex.value].startTime =
    cycleStart;
};

const selectIndexChange = async (n: number) => {
  // const check = await refForm.value.validate();
  // if (!check) return;
  // console.log(formData.value);

  selectIndex.value = n;
};
const formDataLength = computed({
  get: () => {
    return formData.value.personnelAssessmentOption.length;
  },
  set: (n) => {
    changeExamineNumber(n);
  }
});
const changeExamineNumber = (n: number) => {
  if (selectIndex.value >= n) {
    selectIndex.value = n - 1;
  }
  if (n < formData.value.personnelAssessmentOption.length) {
    // selectIndex.value = n - 1;
    formData.value.personnelAssessmentOption.length = n;
    return;
  }
  const { userId } = formData.value;
  const len = formData.value.personnelAssessmentOption.length;
  const num = n - len;
  const objArr: ProbationExamine[] = [];
  for (let i = 1; i <= num; i++) {
    const name = `${
      formData.value.personnelAssessmentOption[0].userInfo.name
    }的第${len + i}次试用期考核`;
    const obj: ProbationExamine = {
      // userId,
      selectIndex: len + i,
      name,
      organizationEvaluation: 100,
      optionStatus: 1
    };
    objArr.push(obj);
    formData.value.personnelAssessmentOption?.push({
      ...probationExamineBaseInfo,
      selectIndex: len + i,
      name,
      userId: formData.value.personnelAssessmentOption[0].userId,
      userInfo: {
        name: formData.value.personnelAssessmentOption[0].userInfo.name
      }
    });
  }
  const examLen = formData.value.personnelAssessmentOption.length;
  const remainder = 100 % examLen; //取模
  const weight = Math.floor(100 / examLen); //商
  let isAddRemainder = false; //余数是否已经新增过
  formData.value.personnelAssessmentOption?.forEach((item) => {
    item.weight = weight;
    if (!isAddRemainder) {
      item.weight += remainder;
      isAddRemainder = true;
    }
  });
};
const userChange = () => {
  //
};
const probationExamineBaseInfo = {
  cycleStart: '',
  cycleEnd: '',
  organizationEvaluation: 100,
  // earlyWarningTime: '',
  optionStatus: 1,
  passScore: 0,
  personnelAbilityQualityIndexLibrary: [],
  personnelAddSubtractIndexLibrary: [],
  personnelAssessmentOptionDimensionality: [],
  personnelKeyPerformanceIndexLibrary: [],
  personnelTargetIndexLibrary: [],
  personnelVetoIndexLibrary: [],
  personnelWorkPlanIndexLibrary: []
};
const disabledDate = (date: any) => {
  const { cycleStart, cycleEnd } =
    formData.value.personnelAssessmentOption[selectIndex.value];
  const startDate = dayjs(cycleStart);
  // const endDate = dayjs(cycleEnd);
  return date > startDate;
};
const personList = ref<any>();
const getPersonList = async () => {
  personList.value = await getProbationPersonnelList({
    type: 2,
    pageNumber: 0,
    pageSize: 10
  });
};
onMounted(() => {
  getPersonList();
});
const visible = ref(false);

const refInput = ref();
const focus = () => {
  refInput.value[0].blur(); //使失去焦点，防止键盘输入
  // visible.value = true;
  humanRosterVisible.value = true;
};
const humanRosterVisible = ref(false);
const selectHuman = (data: any) => {
  formData.value.userId = data.id;
  formData.value.userInfo = { name: data.name };
  formData.value.personnelAssessmentOption?.forEach((item, index) => {
    item.userId = data.id;
    item.userInfo = { name: data.name };
    item.name = `${data.name}的第${index + 1}次试用期考核`;
  });
};
defineExpose({ validate });
</script>

<style lang="less" scoped>
.index {
  width: 800px;
  margin: 0 auto;
}

.custom-radio-card {
  // padding: 10px 16px;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  width: 80px;
  height: 40px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-radio-card1 {
  // padding: 10px 16px;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  width: 40px;
  height: 40px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-radio-card-title {
  color: var(--color-text-1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  // font-weight: bold;
  // margin-bottom: 8px;
}

.custom-radio-card:hover,
.custom-radio-card-checked,
.custom-radio-card:hover .custom-radio-card-mask,
.custom-radio-card-checked .custom-radio-card-mask {
  border-color: rgb(var(--primary-6));
}

.custom-radio-card-checked {
  background-color: var(--color-primary-light-1);
}

.custom-radio-card:hover .custom-radio-card-title,
.custom-radio-card-checked .custom-radio-card-title {
  color: rgb(var(--primary-6));
}

.custom-radio-card-checked .custom-radio-card-mask-dot {
  background-color: rgb(var(--primary-6));
}
</style>
